import {
  Button,
  Image,
  message,
  notification,
  Space,
  TypographyText,
  Upload
} from 'ant-design-vue'
import moment from 'moment'
import { defineComponent, nextTick, onMounted, PropType, ref, watch } from 'vue'
import { useRouter } from 'vue-router'

import aiTestSkinApi from '@/apis/aiTestSkinApi'
import { dataCountItem, timesItem } from '@/apis/aiTestSkinTypes'
import { importOrders } from '@/apis/riverTypes'
import { type ProTableProps, type ProTableRef, ProTable } from '@/components'
import { TABLE_FORMAT, TABLE_ITEM_RENDER, TABLE_RENDERER } from '@/constants'
import { useDialog } from '@/hooks'
import { bus, download, downloadLink, optionsToMap } from '@/utils'
import { handlePrice } from '@/utils/bsshow'

export default defineComponent({
  name: 'JdgGoodsManage',
  props: {
    peoples: {
      type: Array as PropType<Array<importOrders>>,
      required: true
    }
  },
  emits: ['dataCallback'],
  setup(props, { emit }) {
    const skinTimes = ref({} as timesItem)
    const newRowNum = ref([] as Array<dataCountItem>)
    const showSetPriceDlg = ref(false)
    const optionGoodsItemCur = ref({} as any)
    const syncLoading = ref(false)
    const peopleList = ref(props.peoples as any[])
    const showSortDialog = ref(false)
    const dialogLoading = ref(false)
    const { showConfirm } = useDialog()
    const sourceOptions = [
      { label: '自研营销', value: 1 },
      { label: '轻姿颜', value: 2 }
    ]
    const sexOptions = [
      { label: '未知', value: 0 },
      { label: '男', value: 1 },
      { label: '女', value: 2 }
    ]
    const statusOptions = [
      { label: '检测中', value: 0 },
      { label: '成功', value: 1 },
      { label: '失败', value: 2 }
    ]
    const tableRef = ref({} as ProTableRef)
    const tableConfig = ref({
      fixedHeight: true,
      options: {
        border: true,
        align: 'center',
        toolbarConfig: {
          slots: {
            buttons: 'batchButtons'
          }
        },
        formConfig: {
          items: [
            {
              title: '测肤时间',
              field: 'timeRange',
              itemRender: {
                name: TABLE_ITEM_RENDER.FormItemDate,
                props: {
                  type: 'range',
                  placeholder: ['开始时间', '结束时间'],
                  valueFormat: 'x',
                  showTime: {
                    defaultValue: [
                      moment('00:00:00', 'HH:mm:ss'),
                      moment('23:59:59', 'HH:mm:ss')
                    ]
                  },
                  keys: ['startTime', 'endTime']
                }
              }
            },
            {
              title: '测肤人昵称',
              field: 'nickName',
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '请输入',
                  allowClear: true
                }
              }
            },
            {
              title: '手机号',
              field: 'mobile',
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '请输入',
                  allowClear: true
                }
                // options: upDownStatusOptions
              }
            },
            {
              title: '来源',
              field: 'source',
              itemRender: {
                name: TABLE_ITEM_RENDER.ASelect,
                props: {
                  placeholder: '全部',
                  allowClear: true
                },
                options: sourceOptions
              }
            },
            {
              itemRender: {
                name: TABLE_RENDERER.FormItemBtns
              }
            }
          ]
        },
        columnConfig: {
          minWidth: 100,
          resizable: true
        },
        checkboxConfig: {
          showHeader: true,
          range: true
        },
        columns: [
          {
            type: 'checkbox',
            width: 50
          },
          {
            title: '来源',
            field: 'source',
            formatter: ({ cellValue }) => {
              return optionsToMap(sourceOptions)[cellValue]
            }
          },
          {
            title: 'ID',
            field: 'id'
          },
          {
            title: '检测图片',
            field: 'detectionImg',
            width: 200,
            slots: {
              default: 'img'
            }
          },
          {
            title: '昵称',
            field: 'nickname'
          },
          {
            title: '手机号',
            field: 'mobile',
            width: 250
          },
          {
            title: '性别',
            field: 'sex',
            formatter: ({ cellValue }) => {
              return optionsToMap(sexOptions)[cellValue]
            }
          },
          {
            title: '检测时间',
            field: 'createTime',
            width: 210,
            formatter: [TABLE_FORMAT.Date, 'yyyy-MM-dd HH:mm:ss']
          },
          {
            title: '检测状态',
            field: 'status',
            formatter: ({ cellValue }) => {
              return optionsToMap(statusOptions)[cellValue]
            },
            width: 120
          },
          {
            title: '备注',
            field: 'failRemark'
          },
          {
            title: '操作',
            fixed: 'right',
            slots: {
              default: 'operation'
            },
            width: 150
          }
        ],
        pagerConfig: {
          pageSize: 15
        },
        proxyConfig: {
          seq: true,
          form: true,
          props: {
            result: 'dataList',
            total: 'page.totalCount'
          },
          ajax: {
            query: async ({ page, form }) => {
              const data = await aiTestSkinApi.getAnalysisList({
                pageParameter: {
                  pageSize: page.pageSize,
                  currentPage: page.currentPage
                },
                ...form
              })
              return data
            }
          }
        }
      }
    } as ProTableProps)

    onMounted(() => {
      bus.on('refreshJdgGoodsList', () => {
        nextTick(() => {
          tableRef.value.refresh()
        })
      })
      getDetail()
    })
    //获取选中的项
    function getSelectedItems() {
      return tableRef.value.table?.getCheckboxRecords()
    }
    //批量删除
    function handleBatchDelete() {
      const selected = tableRef.value.table.getCheckboxRecords().map(v => v.id)
      console.log(selected)
      if (selected.length === 0) {
        return message.warn('请选择至少1条记录')
      }

      showConfirm({
        content: '确认批量删除？',
        onOk: async () => {
          tableRef.value.refresh(async () => {
            await aiTestSkinApi.getAnalysisDelete({
              ids: selected
            })
            notification.success({
              message: '批量删除成功',
              duration: 1.5
            })
          })
        }
      })
    }
    const router = useRouter()
    //逐条删除
    function handleDelete(row) {
      const selected = [row.id]
      showConfirm({
        content: '确认删除？',
        onOk: () => {
          tableRef.value.refresh(async () => {
            await aiTestSkinApi.getAnalysisDelete({ ids: selected })
            notification.success({
              message: '删除成功',
              duration: 1.5
            })
          })
        }
      })
    }
    async function getDetail() {
      try {
        skinTimes.value = await aiTestSkinApi.getAnalysisTestList()
        console.log(skinTimes.value, 'skinTimes.value')
      } finally {
      }
    }
    //导出
    async function handleExport() {
      const { form } = tableRef.value.table.getProxyInfo()!

      try {
        tableRef.value.showLoading()
        const res = await aiTestSkinApi.getAnalysisExport(form)
        download(res, '测肤数据统计列表')
      } finally {
        tableRef.value.hideLoading()
      }
    }
    function handlePreview(row) {
      router.push({ name: 'SkinDataCountDetail', query: { id: row.id } })
    }
    //刷新回调
    async function refresh() {
      await tableRef.value.table.commitProxy('query')
    }
    function handleRefresh(data) {
      peopleList.value = data
    }

    return {
      tableRef,
      tableConfig,
      showSetPriceDlg,
      optionGoodsItemCur,
      syncLoading,
      showSortDialog,
      dialogLoading,
      peopleList,
      skinTimes,
      handlePreview,
      handleExport,
      handleRefresh,
      handleBatchDelete,
      handleDelete,
      getSelectedItems
    }
  },
  render() {
    return (
      <div>
        <ProTable
          ref="tableRef"
          v-slots={{
            img: ({ row }) => (
              <Image
                style={{
                  width: '100px',
                  height: '100px',
                  objectFit: 'contain'
                }}
                src={row.detectionImg}
              ></Image>
            ),
            batchButtons: () => (
              <Space>
                <Button type="primary" onClick={this.handleBatchDelete}>
                  批量删除
                </Button>
                <Button
                  // loading={this.exportLoading}
                  type="primary"
                  onClick={this.handleExport}
                >
                  导出数据
                </Button>
                <Space>
                  <span>总计累计测肤次数{this.skinTimes.total}次</span>
                  <span>累计测肤人数{this.skinTimes.totalPeople}人；</span>
                  <span>今日测肤次数{this.skinTimes.totalToday}次；</span>
                  <span>今日测肤人数{this.skinTimes.totalTodayPeople}次；</span>
                </Space>
              </Space>
            ),
            salePrice: ({ row }) => {
              return <Space>{handlePrice(row.salePrice, row.saleGold)}</Space>
            },
            isSettlement: ({ row }) => {
              return (
                <Space>
                  {row.isSettlement == 0 ? (
                    <TypographyText type="danger">否</TypographyText>
                  ) : (
                    <TypographyText type="success">是</TypographyText>
                  )}
                </Space>
              )
            },
            operation: ({ row }) => (
              <Space>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handlePreview(row)}
                >
                  查看报告
                </Button>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleDelete(row)}
                >
                  删除
                </Button>
              </Space>
            )
          }}
          {...this.tableConfig}
        />
      </div>
    )
  }
})
